/*
This software has been developed by Ralph M. Butler for the 
sole use of his students.  No one else may copy any part 
of it for any reason, except with explicit permission.
*/

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>
#include <varargs.h>

caddr_t create_shmem();

int myid;
int pagesize;

main(argc,argv)
int argc;
char **argv;
{
    int i, j, rc;
    char *sp;

    pagesize = getpagesize();
    myid = 0;
    sp = (char *) create_shmem(pagesize);
    sp[0] = 0;  /* empty; probably redundant */

    for (i=1; i < 2; i++)
    {
	rc = fork();
	if (rc < 0)
	{
	    dprintf("fork %d failed \n",i);
	    exit(99);
	}
	if (rc == 0)  /* child process */
	{
	    myid = i;
	    while (!sp[0])
		usleep(100);
	    dprintf("spval=%c\n",(char) sp[8191]);
	    sp[0] = 0;
	    exit(0);
	}
    }

    /* process 0 */
    for (i=1; i < pagesize; i++)  /* start at 1; past full ind */
    {
	sp[i] = 'R';
    }
    sp[0] = 1;  /* full */
    while (sp[0])
	usleep(100);
}



caddr_t create_shmem(nbytes)
int nbytes;
{
    int i,mmfd;
    caddr_t mmp, shmem;

    shmem = (caddr_t) malloc(2*pagesize);
    mmp = mmap(shmem,nbytes,PROT_READ|PROT_WRITE|PROT_EXEC,
	       MAP_ANONYMOUS|MAP_SHARED|MAP_VARIABLE,-1,0);
    if (mmp == (caddr_t) -1)
    {
	dprintf("mmap failed: mmp=%d  errno=%d  %s\n",mmp,errno,sys_errlist[errno]);
	exit(99);
    }
    dprintf("shmem=%x mmp=%x \n",shmem,mmp);
    return(mmp);
}

dprintf(fmt, va_alist)
char *fmt;
va_dcl
{
    va_list ap;

    printf("%d: ",myid);
    va_start(ap);
    vprintf(fmt, ap);
    va_end(ap);
    fflush(stdout);
}
